package com.google.code.c2dmtester;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity
{
    public final static String REGISTRATION_ID = "regid";
    public final static String URL             = "url";

    /** Called when the activity is first created. */
    @Override
    public void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main );

        String registrationId = this.readRegistrationId();
        this.setRegistrationId( registrationId );

        EditText et = (EditText) findViewById( R.id.editTextPackageName );
        et.setText( this.getClass().getPackage().getName() );
    }

    private String readRegistrationId()
    {
        SharedPreferences sharedPreferences = PreferencesActivity.getSharedPreferences( this );
        final String registrationId = sharedPreferences.getString( PreferencesActivity.PREF_REGISTRATION_ID, "" );

        return registrationId;
    }

    @Override
    public boolean onCreateOptionsMenu( Menu menu )
    {
        getMenuInflater().inflate( R.menu.options, menu );
        return super.onCreateOptionsMenu( menu );
    }

    @Override
    public boolean onOptionsItemSelected( MenuItem item )
    {
        switch( item.getItemId() )
        {
            case R.id.menuItemPreferences:
                Intent prefsIntent = new Intent( this, PreferencesActivity.class );
                startActivity( prefsIntent );
                return true;
            case R.id.menuItemExit:
                finish();
                return true;
        }
        return super.onOptionsItemSelected( item );
    }

    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();

        Intent intent = getIntent();
        this.onNewIntent( intent );
    }

    private void setRegistrationId( String registrationId )
    {
        EditText editReg = (EditText) findViewById( R.id.editRegistrationID );
        editReg.setText( (CharSequence) registrationId );

        ToggleButton tb = (ToggleButton) findViewById( R.id.toggleButton1 );
        tb.setChecked( null != registrationId && registrationId.length() > 0 );
    }

    @Override
    protected void onNewIntent( Intent intent )
    {
        // TODO Auto-generated method stub
        super.onNewIntent( intent );

        // clear notification (if set)
        final NotificationManager nm = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
        nm.cancel( C2dmReceiver.NOTIFICATION_ID );

        intent = getIntent();

        final Bundle extras = intent.getExtras();
        String url = intent.getDataString();
        if( extras != null )
        {
            String registrationId = extras.getString( REGISTRATION_ID );
            // String url = extras.getString(URL);

            if( null != registrationId )
            {
                this.setRegistrationId( registrationId );

                saveRegistrationId( registrationId );

                Log.i( "regid", registrationId );
            }
        }
        if( null != url )
        {
            Toast.makeText( getBaseContext(), "url: " + url, Toast.LENGTH_LONG ).show();
            Log.i( "url", url );
        }

    }

    private void saveRegistrationId( String registrationId )
    {
        SharedPreferences sharedPreferences = PreferencesActivity.getSharedPreferences( this );
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString( PreferencesActivity.PREF_REGISTRATION_ID, registrationId );
        boolean success = editor.commit();
        // Toast.makeText(this, success ? "saved" : "error", Toast.LENGTH_SHORT).show();
    }

    public void onClickShare( View view )
    {
        Log.i( "event", "share" );
        EditText editReg = (EditText) findViewById( R.id.editRegistrationID );
        String regid = editReg.getText().toString();

        EditText editPackage = (EditText) findViewById( R.id.editTextPackageName );
        String packageName = editPackage.getText().toString();

        String message = "package name: " + packageName + "\nregistration ID: " + regid;

        Intent sharingIntent = new Intent( Intent.ACTION_SEND );
        sharingIntent.setType( "text/plain" );
        sharingIntent.putExtra( android.content.Intent.EXTRA_TEXT, message );
        startActivity( Intent.createChooser( sharingIntent, "Share Registration ID Using" ) );
    }

    public void onClickToggle( View view )
    {
        Log.i( "event", "click" );
        // Toast.makeText(context, "toogle", 1000);
        ToggleButton tb = (ToggleButton) findViewById( R.id.toggleButton1 );
        boolean b = tb.isChecked();
        Log.i( "status", b ? "checked" : "unchecked" );

        if( b )
        {
            this.register();
        }
        else
        {
            this.unregister();
        }

    }

    private void register()
    {
        Toast.makeText( getBaseContext(),
                "registering...",
                Toast.LENGTH_LONG ).show();

        Intent registrationIntent = new Intent( "com.google.android.c2dm.intent.REGISTER" );
        registrationIntent.putExtra( "app", PendingIntent.getBroadcast( this, 0, new Intent(), 0 ) ); // boilerplate
        registrationIntent.putExtra( "sender", getString( R.string.c2dm_sender_id ) );
        startService( registrationIntent );
    }

    private void unregister()
    {
        Toast.makeText( getBaseContext(),
                "unregistering",
                Toast.LENGTH_SHORT ).show();

        Intent unregIntent = new Intent( "com.google.android.c2dm.intent.UNREGISTER" );
        unregIntent.putExtra( "app", PendingIntent.getBroadcast( this, 0, new Intent(), 0 ) );
        startService( unregIntent );

        setRegistrationId( "" );
        saveRegistrationId( "" );
        // nothing to do in this demo
    }

}
